package com.zlm.app.partner.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlm.app.partner.service.UserPartnerService;
import com.zlm.common.constants.CodeConstants;
import com.zlm.common.dto.JsonResultDto;
import com.zlm.common.dto.userEmp.LoginAppParamsDto;
import com.zlm.common.dto.userPartner.SysPartnerDto;
import com.zlm.common.entity.UserTokenDO;
import com.zlm.common.util.CheckParamsUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 合伙人版
 * @Author: duyufu
 * @Date: 2019/7/10 9:36
 */
@RestController
@RequestMapping("/loginPart")
public class LoginPartController extends CheckController{

    @Autowired
    private UserPartnerService userPartnerService;

    /*@Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    private static RedisTemplate<String, Serializable> redisCache;

    @PostConstruct
    public void init() {
        redisCache = this.redisCacheTemplate;
    }

    @GetMapping("/redisTest")
    public void redisTest() {
        String accessToken = (String)redisCache.opsForValue().get("accessToken");
        System.out.println(accessToken);
    }*/

    /**
     * 发送验证码
     * @param mobile
     * @return
     */
    @GetMapping("/sendVerificationCode")
    @ResponseBody
    public JsonResultDto sendVerificationCode(String mobile){
        try {
            //正则校验手机号是否格式正确
            if(!CheckParamsUtils.checkMobile(mobile)) {
                throw new RuntimeException(CodeConstants.CODE_10001);
            }
            //获取短信验证码
            JsonResultDto result = userPartnerService.sendActivation(mobile);
            checkJsonResultDto(result);
            //判断用户是否已经注册
            JsonResultDto verifyResult = userPartnerService.isExistPart(mobile);
            checkJsonResultDto(verifyResult);
            Map<String,Object> phoneStatus = new HashMap<String,Object>(1);
            if ((Boolean)verifyResult.getData()){
                phoneStatus.put("phoneStatus",1);
                //用户已经注册
                return success(phoneStatus);
            }else {
                phoneStatus.put("phoneStatus",0);
                //用户未注册
                return success(phoneStatus);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 验证码注册登录
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/activationLogin")
    @ResponseBody
    public JsonResultDto activationLogin(LoginAppParamsDto loginAppParamsDto) {
        try {
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginAwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            String mobile = loginAppParamsDto.getMobile();
            JsonResultDto result = userPartnerService.checkActivation(loginAppParamsDto.getActivationCode(),
                    loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            //判断用户是否已经注册
            JsonResultDto verifyResult = userPartnerService.isExistPart(mobile);
            checkJsonResultDto(verifyResult);
            JsonResultDto loginResult = null;
            if ((Boolean)verifyResult.getData()) {
                //已注册
                loginResult = userPartnerService.loginPartner(mobile);
                checkJsonResultDto(loginResult);
            } else {
                loginResult = userPartnerService.activationLogin(mobile);
                checkJsonResultDto(loginResult);
            }
            ObjectMapper mapper = new ObjectMapper();
            SysPartnerDto sysPartnerDto = mapper.convertValue(loginResult.getData(), SysPartnerDto.class);
            Map<String, Object> login = new HashMap<>(2);
            login.put("token",sysPartnerDto.getToken());
            login.put("loginPartner",sysPartnerDto);
            return success(login);
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }


    /**
     * app密码登录
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/loginPwd")
    @ResponseBody
    public JsonResultDto loginPwd(LoginAppParamsDto loginAppParamsDto) {
        try {
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginPwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userPartnerService.queryPartByMobileAndPassword(loginAppParamsDto.getMobile(),
                    loginAppParamsDto.getPassword());
            checkJsonResultDto(result);
            JsonResultDto loginResult = userPartnerService.loginPartner(loginAppParamsDto.getMobile());
            checkJsonResultDto(loginResult);
            return success(loginResult.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }


    /**
     * 根据手机号修改密码
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public JsonResultDto updatePassword(LoginAppParamsDto loginAppParamsDto) {
        try {
            //检查参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkUpdatePwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userPartnerService.checkActivation(loginAppParamsDto.getActivationCode(),
                    loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            JsonResultDto updateResult = userPartnerService.updatePassword(loginAppParamsDto.getMobile(),
                    loginAppParamsDto.getPassword());
            checkJsonResultDto(updateResult);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 合伙人设置密码
     * @param token
     * @param password
     * @param restPassword
     * @return
     */
    @GetMapping("/setPassword")
    public JsonResultDto setPassword(String token, String password, String restPassword) {
        try {
            if (!password.equals(restPassword)){
                throw new RuntimeException(CodeConstants.CODE_10017);
            }
            //判断token失效
            UserTokenDO userToken = checkToken(token);
            JsonResultDto result = userPartnerService.setPassword(userToken.getUserId(),password);
            checkJsonResultDto(result);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 更改手机号
     * @param token
     * @param mobile
     * @param activationCode
     * @return
     */
    @GetMapping("/changePhone")
    public JsonResultDto changePhone(String token, String mobile, String activationCode) {
        try {
            //正则校验手机号是否格式正确
            if(!CheckParamsUtils.checkMobile(mobile)) {
                throw new RuntimeException(CodeConstants.CODE_10001);
            }
            //判断token失效
            UserTokenDO userToken = checkToken(token);
            //判断手机号是否已经注册
            JsonResultDto verifyResult = userPartnerService.isExistPart(mobile);
            checkJsonResultDto(verifyResult);
            if ((Boolean)verifyResult.getData()) {
                //已注册
                throw new RuntimeException(CodeConstants.CODE_102);
            }
            //检查验证码
            JsonResultDto checkResult = userPartnerService.checkActivation(activationCode, mobile);
            checkJsonResultDto(checkResult);
            JsonResultDto result = userPartnerService.changePhone(userToken.getUserId(),mobile);
            checkJsonResultDto(result);
            return success();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }



    /**
     * 根据token修改密码
     * @param token
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @GetMapping("/updatePasswordByToken")
    public JsonResultDto updatePasswordByToken(String token,String oldPassword,String newPassword) {
        try {
            //判断token失效
            UserTokenDO userToken = checkToken(token);
            JsonResultDto result = userPartnerService.updatePasswordByToken(userToken.getUserId(),oldPassword,newPassword);
            checkJsonResultDto(result);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }


}
